#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import os
import random
import time
from multiprocessing import Process, JoinableQueue


def producer(q):
    time.sleep(random.randint(1, 3))
    for i in range(3):
        time.sleep(random.randint(1, 3))
        print("\033[45m{} 生产了包子{}\033[0m".format(os.getpid(), i))
        q.put(i)


def consume(q):
    while True:  # 循环从生产者队列中取
        time.sleep(random.randint(1, 3))
        print("{} 消费了 包子{}".format(os.getpid(), q.get()))
        q.task_done()  # 通告队列已经取了一个了


if __name__ == '__main__':
    q = JoinableQueue()  # 封装了Queue的对象

    p1 = Process(target=producer, args=(q,))
    p2 = Process(target=producer, args=(q,))
    c1 = Process(target=consume, args=(q,))

    c1.daemon = True

    p1.start()
    p2.start()
    c1.start()

    p1.join()
    p2.join()
    c1.join()

    q.join()  # 等待生产者队列都被取完

    print("主")
